package hihocode;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class EscapeMazeII1519 {

	private static final char START = 'S';
	private static final char OBSTACLE = '#';
	private static final char EXIT = 'T';
	
	public static final int[][] dir = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
	private static final int MAX = 502; 
	
	private int minMinute = Integer.MAX_VALUE;
	
	private int rows, columns; 
	private char[][] maze = new char[MAX][MAX];
	private boolean[][] visited = new boolean[MAX][MAX];
	
	
	public static void main(String[] args) {
		EscapeMazeII1519 object = new EscapeMazeII1519();
		object.getRes();
	}
	
	public void getRes(){
		Scanner scanner = new Scanner(System.in);
		int startX = 0, startY = 0;
		while(scanner.hasNext()){
			minMinute = Integer.MAX_VALUE;
			rows = scanner.nextInt();
			columns = scanner.nextInt();
			for (int j = 0; j < rows; j++) {
				String string = scanner.next();
				int index = string.indexOf(START);
				if(startX == 0 && index != -1){
					startX = j;
					startY = index;
				}
				maze[j] = string.toCharArray();
			}
			bfs(startX, startY);
			if(minMinute == Integer.MAX_VALUE){
				System.out.println(-1);
			}else{
				System.out.println(minMinute);
			}
		}
		scanner.close();
	}
	
	
	class Node{
		int x, y;
		int curve;
		
		public Node() {
		}
		Node(int x, int y) {  
	        this.x = x;  
	        this.y = y;  
	    } 
	}
	
	//这道题的关键是判断什么时候能够转弯，融合了深度搜索的广度优先搜索
	//根据HDU1728 改写
	//Runtime: 2011ms
	public void bfs(int x, int y){
		
		Queue<Node> queue = new LinkedList<>();
		Node temp = new Node(x, y);
		for(int i = 0; i < rows; i++){
			Arrays.fill(visited[i], false);
		}
		visited[x][y] = true;
		//由于题意初始不管往哪个方向都不算转弯，所以初始为-1
		temp.curve = -1;
		queue.add(temp);
		while(!queue.isEmpty()){
			temp = queue.poll();
			if(maze[temp.x][temp.y] == EXIT){  
				//到达终点
				minMinute = temp.curve;
	            return;
	        }
//			//因为前面搜完了一个方向，就肯定会拐弯，所以要+1，也因此起点的k初始化为-1;
			for (int i = 0; i < dir.length; i++) {
				int curX = temp.x + dir[i][0];
				int curY = temp.y + dir[i][1];
				
				//搜完一个方向 ,直到遇到障碍物或者墙
				//注意这道题的关键就是遇到墙或者障碍物才能转弯
				while (curX >= 0 && curX < rows && curY >= 0 && curY < columns
						&& maze[curX][curY] != OBSTACLE){
					if (!visited[curX][curY]) {
						if(maze[curX][curY] == EXIT){  
							//到达终点
							minMinute = temp.curve + 1;
				            return;
				        }
					}
					//因为我们要判断转弯，所以我们就继续往该方向的前面走
					//如果遇到了终点，我们此时肯定将值加进去了，之后再出队的时候，一定会遇到该值
					//继续沿着该方向走
					curX += dir[i][0];
					curY += dir[i][1];
				}
				//此时说明遇到了墙或者障碍物
				curX -= dir[i][0];
				curY -= dir[i][1];
				if(!visited[curX][curY]){
					visited[curX][curY] = true;
					Node cur = new Node(curX, curY);
					cur.curve = temp.curve + 1;
					queue.add(cur);
				}
			}
		}
	}
}
